package main

import (
	"fmt"
	"net/http"
	"time"

	"nh-poc/pkg/common"
	"nh-poc/pkg/rest"
	"nh-poc/pkg/utils"

	"github.com/gin-gonic/gin"
)

var (
	ReportUrl string
)

func ReportEvent() {

	client := rest.NewRestClient()
	var err error

	index := 0
	for {
		if ReportUrl == "" {
			fmt.Println("ReportUrl is empty.")
			time.Sleep(3 * time.Second)
			continue
		}

		err = client.ReportEvent(ReportUrl, &common.HKEvent{
			ID:      "event-001",
			Event:   "car_in",
			Created: time.Now().Unix(),
			Data: map[string]interface{}{
				"car_number": "川A12345",
				"car_color":  "blue",
			},
		})
		if err != nil {
			fmt.Println("ReportEvent error: ", err)
			time.Sleep(3 * time.Second)
			continue
		}

		index += 1
		fmt.Printf("ReportEvent(%s) %d\n", ReportUrl, index)
		time.Sleep(3 * time.Second)
	}
}

func main() {
	fmt.Println("video-service is start.")
	//gin.SetMode(gin.ReleaseMode)
	// 创建一个默认的 Gin 路由器
	r := gin.Default()

	// 定义一个 GET 路由
	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"msg": "Hello, video-service!",
		})
	})

	// 设置事件上报地址接口
	r.POST("/webhook", func(c *gin.Context) {
		reportUrl := c.DefaultQuery("reportUrl", "")

		if !utils.IsValidUrl(reportUrl) {
			fmt.Println("reportUrl is not valid.")
			c.JSON(http.StatusOK, gin.H{
				"msg": "reportUrl is not valid.",
			})
			return
		}

		fmt.Printf("reportUrl=%s\n", reportUrl)
		ReportUrl = reportUrl

		c.JSON(http.StatusOK, gin.H{
			"msg": "set webhook reportUrl is ok.",
		})
	})

	// 启动一个协程，上报事件
	go ReportEvent()

	r.Run(":9091")

}
